// implementation of generic tools

#include "cube.h"

////////////////////////// rnd numbers ////////////////////////////////////////

#define N              (624)             
#define M              (397)                
#define K              (0x9908B0DFU)       
#define hiBit(u)       ((u) & 0x80000000U)  
#define loBit(u)       ((u) & 0x00000001U)  
#define loBits(u)      ((u) & 0x7FFFFFFFU)  
#define mixBits(u, v)  (hiBit(u)|loBits(v)) 

static uint state[N+1];     
static uint *next;          
static int left = -1;     

void seedMT(uint seed)
{
    register uint x = (seed | 1U) & 0xFFFFFFFFU, *s = state;
    register int j;
    for(left=0, *s++=x, j=N; --j; *s++ = (x*=69069U) & 0xFFFFFFFFU);
}

uint reloadMT(void)
{
    register uint *p0=state, *p2=state+2, *pM=state+M, s0, s1;
    register int j;
    if(left < -1) seedMT(time(NULL));
    left=N-1, next=state+1;
    for(s0=state[0], s1=state[1], j=N-M+1; --j; s0=s1, s1=*p2++) *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
    for(pM=state, j=M; --j; s0=s1, s1=*p2++) *p0++ = *pM++ ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
    s1=state[0], *p0 = *pM ^ (mixBits(s0, s1) >> 1) ^ (loBit(s1) ? K : 0U);
    s1 ^= (s1 >> 11);
    s1 ^= (s1 <<  7) & 0x9D2C5680U;
    s1 ^= (s1 << 15) & 0xEFC60000U;
    return(s1 ^ (s1 >> 18));
}

uint randomMT(void)
{
    uint y;
    if(--left < 0) return(reloadMT());
    y  = *next++;
    y ^= (y >> 11);
    y ^= (y <<  7) & 0x9D2C5680U;
    y ^= (y << 15) & 0xEFC60000U;
    return(y ^ (y >> 18));
}

void Wrapper::append(const char *fmt, ...) {
	defvformatstring(str, fmt, fmt);

	if(lines.length() == 0) { lines.add(); lines[0].s[0] = 0; }

	char *line = lines[lines.length() - 1].s;

	int sl = strlen(sep);
	int l = strlen(str);

	if(line[0]) l += sl;

	if(l + (int)strlen(line) >= maxlen) {
		lines.add(); line = lines[lines.length() - 1].s;
		line[0] = 0;
	}

	if(l < maxlen) {
		if(line[0]) strcat(line, sep);
			strcat(line, str);
	} else { // line too long, so split it
		char *c = str;
		while(l > 0) {
			strncat(line, c, maxlen-1);
			lines.add(); line = lines[lines.length() - 1].s;
			line[0] = 0;
			l -= maxlen-1;
			c += maxlen-1;
		}
	}
}

char *trim(char *str) {
	if(!str) return NULL;
	while(*str && isspace(*str)) str++;
	int l = strlen(str) - 1;
	while(l >= 0 && isspace(str[l])) str[l--] = 0;
	return str;
}